package com.wclass.common;

import com.gexin.rp.sdk.base.IBatch;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.LinkTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class GeTuiUtil {
    //定义常量, appId、appKey、masterSecret 采用本文档 "第二步 获取访问凭证 "中获得的应用配置
    private static String appId;
    private static String appKey;
    private static String masterSecret;
    private static String url;

    @Value("${getui.appId}")
    public void setAppId(String appId2) {
        appId = appId2;
    }

    @Value("${getui.appKey}")
    public void setAppKey(String appKey2) {
        appKey = appKey2;
    }

    @Value("${getui.masterSecret}")
    public void setMasterSecret(String masterSecret2) {
        masterSecret = masterSecret2;
    }

    @Value("${getui.url}")
    public void setUrl(String url2) {
        url = url2;
    }

    /**
     * 推送到所有app用户
     * @param content             通知栏内容
     * @return
     */
    public static Map pushMessageToApp(String content) {
        try {
            IGtPush push = new IGtPush(url, appKey, masterSecret);

            List<String> appIds = Lists.newArrayList();
            appIds.add(appId);
            AppMessage message;
            IPushResult ret;
            /*
             * ios推送
             */
            TransmissionTemplate iosTemplate = GeTuiUtil.getTemplate(content);

            // 定义"AppMessage"类型消息对象，设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
            message = new AppMessage();
            message.setData(iosTemplate);
            message.setAppIdList(appIds);
            message.setOffline(true);
            message.setOfflineExpireTime(1000 * 600);

            ret = push.pushMessageToApp(message);
            System.out.println(ret.getResponse().toString());

            /*
             * android推送
             */
            NotificationTemplate androidTemplate = notificationTemplate(content);

            // 定义"AppMessage"类型消息对象，设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
            message = new AppMessage();
            message.setData(androidTemplate);
            message.setAppIdList(appIds);
            message.setOffline(true);
            message.setOfflineExpireTime(1000 * 600);

            ret = push.pushMessageToApp(message);
            System.out.println(ret.getResponse().toString());

            return ret.getResponse();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 批量单推功能
     * @return
     */
    public static Map batchPushSingleMessage(String cids, String content){
        IGtPush push = new IGtPush(url, appKey, masterSecret);
        IBatch batch = push.getBatch();

        try {
            //构建客户的透传消息
            String[] cidArr = cids.split(",");
            for (int i = 0;i < cidArr.length;i++){
                constructClientTransMsg(cidArr[i], content, batch);

                constructClientNotiMsg(cidArr[i], content, batch);
            }

            IPushResult ret = batch.submit();
            return ret.getResponse();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 推送到单个app用户
     * @param type android/ios
     * @param transmissionContent 透传消息
     * @param clientId            推送客户端id
     * @return
     */
    public static Map pushMessageToSingle(String type, String clientId, String transmissionContent) throws Exception {
        IGtPush push = new IGtPush(url, appKey, masterSecret);

        /**
         * 单推消息的消息体
         */
        SingleMessage message = new SingleMessage();
        if (type.equals("ios")) {
            TransmissionTemplate template = getTemplate(transmissionContent);
            message.setData(template);
        } else {
            NotificationTemplate template = notificationTemplate(transmissionContent);
            message.setData(template);
        }

        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);

        /**
         * 推送目标
         */
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(clientId);
        //别名推送
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse());
            return ret.getResponse();
        } else {
            return null;
        }
    }

    /**
     * 透传消息模板
     * @return
     */
    public static TransmissionTemplate getTemplate(String content) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent(content);
        template.setTransmissionType(2);
        APNPayload payload = new APNPayload();
        payload.setAutoBadge("+1");
        payload.setContentAvailable(1);
        payload.setSound("default");
        payload.setCategory("$由客户端定义");
        //简单模式APNPayload.SimpleMsg
        payload.setAlertMsg(new APNPayload.SimpleAlertMsg(content));

        template.setAPNInfo(payload);
        return template;
    }

    /**
     * 构建客户的透传消息
     * @param cid
     * @param content
     * @param batch
     * @throws Exception
     */
    private static void constructClientTransMsg(String cid, String content ,IBatch batch) throws Exception {

        SingleMessage message = new SingleMessage();
        TransmissionTemplate template = GeTuiUtil.getTemplate(content);

        message.setData(template);
        message.setOffline(true);
        message.setOfflineExpireTime(1 * 1000);

        // 设置推送目标，填入appid和clientId
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        batch.add(message, target);
    }

    /**
     * 构建客户的通知消息
     * @param cid
     * @param content
     * @param batch
     * @throws Exception
     */
    private static void constructClientNotiMsg(String cid, String content ,IBatch batch) throws Exception {

        SingleMessage message = new SingleMessage();
        NotificationTemplate template = notificationTemplate(content);

        message.setData(template);
        message.setOffline(true);
        message.setOfflineExpireTime(1 * 1000);

        // 设置推送目标，填入appid和clientId
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        batch.add(message, target);
    }

    /**
     * 配置打开应用消息主体信息
     * @return
     */
    private static NotificationTemplate notificationTemplate(String transmissionContent) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        template.setTransmissionContent(transmissionContent);

        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle("喔哦在线教育");
        style.setText(transmissionContent);
        // 配置通知栏图标
        style.setLogo("icon.png");
        // 配置通知栏网络图标
        style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);
        return template;
    }

    /**
     * 打开网页模板
     * @param content
     * @return
     */
    public static LinkTemplate linkTemplate(String content) {
        LinkTemplate template = new LinkTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);

        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle("喔哦在线教育");
        style.setText(content);
        // 配置通知栏图标
//        style.setLogo("icon.png");
        // 配置通知栏网络图标
//        style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);

        // 设置打开的网址地址
        template.setUrl("");
        return template;
    }

    public static void main(String[] args) throws IOException {
        IGtPush push = new IGtPush("http://sdk.open.api.igexin.com/apiex.htm", "zdfF9xvq9I9ufLyOdPJ09A", "kHxkDzZzTxANjdbXVghNrA");

        /*
         * 单推
         */
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId("GZ6fAWrqP47jmNRopNGQV2");
        template.setAppkey("zdfF9xvq9I9ufLyOdPJ09A");
        template.setTransmissionType(2);

        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle("喔哦在线教育");
        style.setText("推送消息");
        // 配置通知栏图标
        style.setLogo("icon.png");
        // 配置通知栏网络图标
        style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);


        /*
         * 单推消息的消息体
         */
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);

        /*
         * 推送目标
         */
        Target target = new Target();
        target.setAppId("GZ6fAWrqP47jmNRopNGQV2");
        target.setClientId("9c85282827ec7bc4767c8d6781ad2327");
        //别名推送
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse());
        }

        /* 群推*/
//        TransmissionTemplate template = new TransmissionTemplate();
//        template.setAppId("GZ6fAWrqP47jmNRopNGQV2");
//        template.setAppkey("zdfF9xvq9I9ufLyOdPJ09A");
//        template.setTransmissionContent("透传消息文本");
//        template.setTransmissionType(2);
//        APNPayload payload = new APNPayload();
//        payload.setBadge(1);
//        payload.setContentAvailable(1);
//        payload.setSound("default");
//        payload.setCategory("$由客户端定义");
//        //简单模式APNPayload.SimpleMsg
//        payload.setAlertMsg(new APNPayload.SimpleAlertMsg("alert msg"));
//        template.setAPNInfo(payload);

//        List<String> appIds = Lists.newArrayList();
//        appIds.add("GZ6fAWrqP47jmNRopNGQV2");

        // 定义"AppMessage"类型消息对象，设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
//        AppMessage message = new AppMessage();
//        message.setData(template);
//        message.setAppIdList(appIds);
//        message.setOffline(true);
//        message.setOfflineExpireTime(1000 * 600);
//
//        IPushResult ret = push.pushMessageToApp(message);
//        System.out.println(ret.getResponse().toString());

//        LinkTemplate template_1 = new LinkTemplate();
//        // 设置APPID与APPKEY
//        template_1.setAppId("GZ6fAWrqP47jmNRopNGQV2");
//        template_1.setAppkey("zdfF9xvq9I9ufLyOdPJ09A");
//
//        Style0 style = new Style0();
//        // 设置通知栏标题与内容
//        style.setTitle("喔哦在线教育");
//        style.setText("推送消息");
//        // 配置通知栏图标
////        style.setLogo("icon.png");
//        // 配置通知栏网络图标
////        style.setLogoUrl("");
//        // 设置通知是否响铃，震动，或者可清除
//        style.setRing(true);
//        style.setVibrate(true);
//        style.setClearable(true);
//        template_1.setStyle(style);
//        // 设置打开的网址地址
//        template_1.setUrl("https://www.baidu.com");
//
//        AppMessage message_1 = new AppMessage();
//        message_1.setData(template_1);
//        message_1.setAppIdList(appIds);
//        message_1.setOffline(true);
//        message_1.setOfflineExpireTime(1000 * 600);
//
//        IPushResult ret_1 = push.pushMessageToApp(message_1);
//        System.out.println(ret_1.getResponse().toString());

    }
}
